package com.helmlabs.grouper.finance.services;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;

import com.helmlabs.grouper.accounts.model.UserProfile;
import com.helmlabs.grouper.accounts.service.AccountManager;
import com.helmlabs.grouper.accounts.service.AccountManagerFactory;
import com.helmlabs.grouper.finance.FinanceApplicationContext;
import com.helmlabs.grouper.finance.dao.MembershipDueDao;
import com.helmlabs.grouper.finance.model.MembershipDueRate;
import com.helmlabs.grouper.finance.model.MembershipDueSchedule;

public class MembershipDueServiceImpl implements MembershipDueService {
	
	private MembershipDueDao membershipDueDao = (MembershipDueDao)FinanceApplicationContext.getInstance().getBean("membershipDueDao");
	private AccountManager accountManager = AccountManagerFactory.getAccountManager();

	public double getPriceForMembership(Long userid) {
		UserProfile profile = accountManager.getUserProfile(userid);
		if (profile ==null)
			throw new RuntimeException("user profile does not exist");
		
		MembershipDueSchedule schedule = membershipDueDao.getSchedule(new Date());
		if (schedule == null){
			throw new RuntimeException("no membership schedule currently exists for this day");
		}
		
		// Test to see if this user is a part of any of the groups 
		// which this rate will apply to
		for(Iterator rates = schedule.getRates().iterator(); rates.hasNext(); ){
			MembershipDueRate rate = (MembershipDueRate)rates.next();
			Set<String> roleIds = rate.getAppliesToGroups();
			for(String roleid : roleIds){
				if (accountManager.isMemberOfRole(userid, new Long(roleid), true)){
					return rate.getAmount();
				}
			}
			
		}
		return 0;
	}
	
	

}
